/**
 * @Author: 安广伟
 * @Email: anguangwei@jwzh.tech
 * @Date: 2024-09-09 15:26:47
 * @LastEditTime 2024-09-09 15:26:47
 * @since: 1.0.0
 * @Version: 1.0.0
 * @Description:
 */

package com.ry.mall.server.aspect.watch;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.text.DecimalFormat;

@Aspect
@Component
@Slf4j
public class TimingAspect {

    @Around("@annotation(timedOperation)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, TimedOperation timedOperation) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(joinPoint.getSignature().getName());
        try {
            // 执行原方法
            return joinPoint.proceed();
        } finally {
            stopWatch.stop();
            // 输出操作摘要和描述以及执行时间
            DecimalFormat df = new DecimalFormat("0.0000000"); // 格式化为两位小数
            String splitLine = "----------------------------------------------------------";
            log.debug("\n" + splitLine + "\n[" + timedOperation.summary() + "],运行耗时:"
                    + df.format(stopWatch.getTotalTimeSeconds()) + "秒.\n" + splitLine);
            // log.debug("【" + timedOperation.summary() + "】");
            // log.debug(" 描述: " + timedOperation.description());
            // log.debug(" 执行耗时: " + df.format(stopWatch.getTotalTimeSeconds()) + "秒");

            // 采用缺省的格式输出
            // log.debug(stopWatch.prettyPrint(TimeUnit.SECONDS));
        }
    }
}
